<script setup lang="ts">
import { ref, computed, defineProps, defineEmits, onMounted } from 'vue'
import { Plus, Delete, Edit, FolderAdd, Document, Folder, ArrowDown, ArrowRight } from '@element-plus/icons-vue'
import { INotebook, INote } from '../types/electron'
import { ElMessage, ElMessageBox } from 'element-plus'

// 定义树节点类型（统一笔记本和笔记）
interface TreeNode extends INotebook {
  type: 'notebook' | 'note';
  notes?: INote[];
  children?: TreeNode[];
}

const props = defineProps<{
  currentNotebook: INotebook | null,
  currentNote: INote | null,
  searchText: string,
  initialExpandedIds?: string[], // 添加初始展开ID列表属性
}>();

const emit = defineEmits([
  'select-notebook', 
  'select-note', 
  'toggle-expand',
  'notebooks-loaded',
  'notes-loaded',
  'notebook-created',
  'notebook-updated',
  'notebook-deleted',
  'note-created',
  'note-updated',
  'note-deleted'
]);

// 数据
const notebooks = ref<INotebook[]>([]);
const notes = ref<INote[]>([]);
const loading = ref(false);

// 展开的笔记本
const expandedNotebooks = ref<Set<string>>(new Set());
const MAX_TREE_DEPTH = 3; // 最大深度限制为3层

// 已加载的笔记本ID集合
const loadedNotebookIds = ref<Set<string>>(new Set());

// 初始化
onMounted(async () => {
  // 设置初始展开状态
  if (props.initialExpandedIds && props.initialExpandedIds.length > 0) {
    props.initialExpandedIds.forEach(id => {
      expandedNotebooks.value.add(id);
    });
    emit('toggle-expand', expandedNotebooks.value);
  }

  // 加载笔记本数据
  await loadNotebooks();
  
  // 加载所有已展开笔记本的笔记
  const loadPromises = Array.from(expandedNotebooks.value).map(notebookId => 
    loadNotes(notebookId)
  );
  await Promise.all(loadPromises);
  
  // 如果有当前笔记本，确保加载其笔记
  if (props.currentNotebook && !expandedNotebooks.value.has(props.currentNotebook.id)) {
    await loadNotes(props.currentNotebook.id);
  }
});

// 清除已加载的笔记本ID缓存
const clearLoadedCache = () => {
  console.log('清除已加载笔记本缓存');
  loadedNotebookIds.value.clear();
};

// 加载笔记本
const loadNotebooks = async () => {
  try {
    console.log('开始加载笔记本...');
    loading.value = true;
    
    // 获取所有笔记本
    const allNotebooks = await window.elec.notebook.getAll();
    console.log(`从数据库加载了 ${allNotebooks.length} 个笔记本`);
    
    // 清除已加载笔记本的缓存
    clearLoadedCache();
    
    // 标准化parent_id - 确保统一使用null表示根层级
    const normalizedNotebooks = allNotebooks.map(notebook => {
      // 如果parent_id是空字符串，转换为null
      if (notebook.parent_id === '') {
        console.log(`标准化笔记本 ${notebook.name} 的parent_id: '' -> null`);
        return { ...notebook, parent_id: null };
      }
      return notebook;
    });
    
    // 更新组件状态
    notebooks.value = normalizedNotebooks;
    notes.value = [];
    
    // 如果没有笔记本，创建一个默认笔记本
    if (notebooks.value.length === 0) {
      console.log('没有笔记本，创建默认笔记本');
      const defaultNotebook = await window.elec.notebook.create({
        name: '默认笔记本',
        description: '默认笔记本',
        order_index: 0,
        parent_id: null,  // 明确指定为null
        is_deleted: 0
      });
      
      notebooks.value.push(defaultNotebook);
    }
    
    // 通知父组件笔记本已加载
    emit('notebooks-loaded', notebooks.value);
    
    // 如果有笔记本，默认展开根级笔记本
    if (notebooks.value.length > 0) {
      const rootNotebooks = notebooks.value.filter(n => !n.parent_id);
      console.log(`找到 ${rootNotebooks.length} 个根级笔记本`);
      rootNotebooks.forEach(n => {
        console.log(`展开根级笔记本: ${n.name} (ID: ${n.id})`);
        expandedNotebooks.value.add(n.id);
      });
      
      // 通知展开状态变更
      emit('toggle-expand', expandedNotebooks.value);
    }

    // 打印笔记本层级关系
    console.log("笔记本层级结构:");
    for (const notebook of notebooks.value) {
      console.log(`${notebook.id} - ${notebook.name} - 父级: ${notebook.parent_id || 'ROOT'}`);
    }
  } catch (error) {
    console.error('加载笔记本失败', error);
    ElMessage.error('加载笔记本失败');
  } finally {
    loading.value = false;
  }
};

// 加载笔记
const loadNotes = async (notebookId: string) => {
  // 如果已经加载过该笔记本的笔记，跳过
  if (loadedNotebookIds.value.has(notebookId)) {
    return;
  }
  
  try {
    loading.value = true;
    const notebookNotes = await window.elec.note.getAllByNotebook(notebookId);
    
    // 添加到已有笔记中
    notes.value = [...notes.value.filter(n => n.notebook_id !== notebookId), ...notebookNotes];
    
    // 标记为已加载
    loadedNotebookIds.value.add(notebookId);
    
    // 通知父组件笔记已加载
    emit('notes-loaded', notes.value);
  } catch (error) {
    console.error('加载笔记失败', error);
    ElMessage.error('加载笔记失败');
  } finally {
    loading.value = false;
  }
};

// 切换展开状态
const toggleExpand = async (notebookId: string) => {
  // 检查是否存在此笔记本
  const notebook = notebooks.value.find(n => n.id === notebookId);
  if (!notebook) {
    console.error(`找不到ID为 ${notebookId} 的笔记本`);
    return;
  }
  
  console.log(`切换笔记本 ${notebook.name} (ID: ${notebook.id}) 的展开状态`);
  
  // 切换展开状态
  if (expandedNotebooks.value.has(notebookId)) {
    console.log(`折叠笔记本 ${notebook.name}`);
    expandedNotebooks.value.delete(notebookId);
  } else {
    console.log(`展开笔记本 ${notebook.name}`);
    expandedNotebooks.value.add(notebookId);
    
    // 加载该笔记本下的笔记，即使没有子项
    try {
      console.log(`加载笔记本 ${notebook.name} 下的笔记`);
      await loadNotes(notebookId);
    } catch (error) {
      console.error('加载笔记失败', error);
    }
  }
  
  // 通知父组件展开状态变更
  emit('toggle-expand', expandedNotebooks.value);
};

// 计算笔记本树结构
const notebookTree = computed(() => {
  // 处理搜索逻辑
  if (props.searchText) {
    const query = props.searchText.toLowerCase();
    
    // 找到匹配的笔记
    const matchedNotes = notes.value.filter(note => 
      note.title.toLowerCase().includes(query) || 
      note.content.toLowerCase().includes(query)
    );
    
    // 找到匹配的笔记本
    const matchedNotebooks = notebooks.value.filter(notebook =>
      notebook.name.toLowerCase().includes(query)
    );
    
    // 构建包含匹配笔记的笔记本ID集合
    const matchedNotebookIds = new Set([
      ...matchedNotes.map(note => note.notebook_id),
      ...matchedNotebooks.map(notebook => notebook.id)
    ]);
    
    // 展开所有匹配的笔记本
    matchedNotebookIds.forEach(id => {
      expandedNotebooks.value.add(id);
      // 同时展开父级笔记本
      let notebook = notebooks.value.find(n => n.id === id);
      while (notebook && notebook.parent_id) {
        expandedNotebooks.value.add(notebook.parent_id);
        notebook = notebooks.value.find(n => n.id === notebook.parent_id);
      }
    });
    
    // 构建树结构，但只包含匹配的笔记本和笔记
    return buildTreeWithSearch(null, matchedNotebookIds, matchedNotes);
  }
  
  // 非搜索状态：构建完整树结构
  return buildTree(null);
});

// 构建普通树结构
const buildTree = (parentId: string | null = null, depth = 1): TreeNode[] => {
  console.log(`buildTree - parentId: ${parentId}, depth: ${depth}`);
  
  if (depth > MAX_TREE_DEPTH) {
    console.log(`达到最大深度 ${MAX_TREE_DEPTH}, 返回空数组`);
    return [];
  }
  
  const result: TreeNode[] = [];
  
  // 获取当前层级的笔记本 - 使用更一致的处理
  const currentLevelNotebooks = notebooks.value
    .filter(n => {
      if (parentId === null) {
        // 处理根级笔记本: parent_id为null或空字符串
        return !n.parent_id || n.parent_id === '';
      }
      // 子级笔记本: parent_id严格匹配
      return n.parent_id === parentId;
    })
    .sort((a, b) => a.order_index - b.order_index);
  
  console.log(`当前层级笔记本(${parentId || 'root'}): ${currentLevelNotebooks.map(n => `${n.name}(${n.id})`).join(', ')}`);
  
  // 添加笔记本及其笔记和子笔记本
  for (const notebook of currentLevelNotebooks) {
    console.log(`处理笔记本: ${notebook.name} (ID: ${notebook.id}, ParentID: ${notebook.parent_id || 'none'})`);
    
    const treeNode: TreeNode = {
      ...notebook,
      type: 'notebook',
      children: []
    };
    
    // 所有子内容只在笔记本展开时显示
    if (expandedNotebooks.value.has(notebook.id)) {
      console.log(`笔记本 ${notebook.name} 是展开状态，加载并显示内容`);
      
      // 加载笔记 - 如果尚未加载
      if (!loadedNotebookIds.value.has(notebook.id)) {
        console.log(`加载笔记本 ${notebook.name} 的笔记`);
        // 异步加载，不等待
        loadNotes(notebook.id).catch(e => console.error('加载笔记失败', e));
      }
      
      // 添加笔记
      const notebookNotes = notes.value
        .filter(n => n.notebook_id === notebook.id)
        .sort((a, b) => new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime());
      
      console.log(`笔记本 ${notebook.name} 下有 ${notebookNotes.length} 条笔记`);
      
      for (const note of notebookNotes) {
        treeNode.children.push({
          ...note,
          type: 'note'
        } as unknown as TreeNode);
      }
      
      // 递归构建子笔记本
      const childNotebooks = buildTree(notebook.id, depth + 1);
      console.log(`笔记本 ${notebook.name} 下有 ${childNotebooks.length} 个子笔记本`);
      
      // 添加子笔记本到当前节点
      treeNode.children = [...treeNode.children, ...childNotebooks];
    } else {
      console.log(`笔记本 ${notebook.name} 是折叠状态，不加载内容`);
    }
    
    result.push(treeNode);
  }
  
  return result;
};

// 构建搜索结果树结构
const buildTreeWithSearch = (
  parentId: string | null = null, 
  matchedNotebookIds: Set<string>,
  matchedNotes: INote[],
  depth = 1
): TreeNode[] => {
  if (depth > MAX_TREE_DEPTH) return [];
  
  const result: TreeNode[] = [];
  
  // 获取当前层级的笔记本
  const currentLevelNotebooks = notebooks.value
    .filter(n => (n.parent_id === parentId) || (!n.parent_id && parentId === null))
    .sort((a, b) => a.order_index - b.order_index);
  
  for (const notebook of currentLevelNotebooks) {
    // 检查该笔记本是否匹配或者包含匹配的笔记
    const notebookMatches = matchedNotebookIds.has(notebook.id);
    
    // 如果笔记本不匹配，且没有匹配的子项，跳过
    if (!notebookMatches && !hasMatchedChildren(notebook.id, matchedNotebookIds, matchedNotes)) {
      continue;
    }
    
    const treeNode: TreeNode = {
      ...notebook,
      type: 'notebook',
      children: []
    };
    
    // 为确保加载该笔记本下的笔记，如果还未加载则异步加载
    if (!loadedNotebookIds.value.has(notebook.id)) {
      // 这里使用异步加载，不等待结果，优先显示UI
      loadNotes(notebook.id);
    }
    
    // 添加当前笔记本下匹配的笔记
    const notebookMatchedNotes = matchedNotes
      .filter(n => n.notebook_id === notebook.id)
      .sort((a, b) => new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime());
    
    for (const note of notebookMatchedNotes) {
      treeNode.children.push({
        ...note,
        type: 'note'
      } as unknown as TreeNode);
    }
    
    // 添加子笔记本
    const childNotebooks = buildTreeWithSearch(notebook.id, matchedNotebookIds, matchedNotes, depth + 1);
    treeNode.children = [...treeNode.children, ...childNotebooks];
    
    result.push(treeNode);
  }
  
  return result;
};

// 检查是否有匹配的子项
const hasMatchedChildren = (
  notebookId: string, 
  matchedNotebookIds: Set<string>,
  matchedNotes: INote[]
): boolean => {
  // 检查是否有匹配的笔记
  if (matchedNotes.some(note => note.notebook_id === notebookId)) {
    return true;
  }
  
  // 检查是否有匹配的直接子笔记本
  const directChildren = notebooks.value.filter(n => n.parent_id === notebookId);
  if (directChildren.some(child => matchedNotebookIds.has(child.id))) {
    return true;
  }
  
  // 递归检查子笔记本
  return directChildren.some(child => 
    hasMatchedChildren(child.id, matchedNotebookIds, matchedNotes)
  );
};

// 获取子笔记本
const getChildNotebooks = (parentId: string) => {
  return notebooks.value
    .filter(n => n.parent_id === parentId)
    .sort((a, b) => a.order_index - b.order_index);
};

// 判断是否有子笔记本
const hasChildNotebooks = (notebookId: string) => {
  console.log(`检查笔记本 ${notebookId} 是否有子笔记本`);
  const hasChildren = notebooks.value.some(n => n.parent_id === notebookId);
  console.log(`笔记本 ${notebookId} ${hasChildren ? '有' : '没有'}子笔记本`);
  return hasChildren;
};

// 获取当前深度
const getNotebookDepth = (notebook: INotebook): number => {
  if (!notebook.parent_id) return 1;
  
  const parent = notebooks.value.find(n => n.id === notebook.parent_id);
  if (!parent) return 1;
  
  return getNotebookDepth(parent) + 1;
};

// 判断是否可以创建子笔记本
const canCreateChildNotebook = (notebook: INotebook): boolean => {
  return getNotebookDepth(notebook) < MAX_TREE_DEPTH;
};

// 手动选择笔记本
const selectNotebook = async (notebook: INotebook) => {
  console.log(`选择笔记本: ${notebook.name}`);
  
  // 如果当前选中的笔记本被再次点击，则切换展开状态
  if (props.currentNotebook?.id === notebook.id) {
    console.log('当前笔记本被再次点击，切换展开状态');
    await toggleExpand(notebook.id);
    // 仍然需要设置为当前选中的笔记本
    emit('select-notebook', notebook);
    return;
  }
  
  // 加载该笔记本下的笔记
  await loadNotes(notebook.id);
  
  // 确保选中的笔记本是展开的，以便显示其笔记
  expandedNotebooks.value.add(notebook.id);
  
  // 如果有父笔记本，也展开父级笔记本
  let parent = notebooks.value.find(n => n.id === notebook.parent_id);
  while (parent) {
    expandedNotebooks.value.add(parent.id);
    parent = notebooks.value.find(n => n.id === parent.parent_id);
  }
  
  emit('toggle-expand', expandedNotebooks.value);
  // 仅通知父组件笔记本被选中，不自动选择笔记
  emit('select-notebook', notebook);
};

// 创建新笔记本
const createNotebook = async (parentId: string | null = null) => {
  try {
    // 保存原始父ID便于调试
    const originalParentId = parentId;
    console.log('开始创建笔记本，原始父ID:', originalParentId);
    
    // 确保parentId是null而不是空字符串
    if (parentId === '') parentId = null;
    
    // 检查深度限制
    if (parentId) {
      const parentNotebook = notebooks.value.find(n => n.id === parentId);
      if (!parentNotebook) {
        console.error(`找不到ID为 ${parentId} 的父笔记本`);
        ElMessage.warning('无法找到指定的父笔记本');
        return null;
      }
      
      if (!canCreateChildNotebook(parentNotebook)) {
        ElMessage.warning(`笔记本最多只能有${MAX_TREE_DEPTH}层`);
        return null;
      }
      
      console.log(`父笔记本存在: ${parentNotebook.name} (ID: ${parentNotebook.id})`);
    }
    
    const name = await ElMessageBox.prompt('请输入笔记本名称', '新建笔记本', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: (value) => !!value.trim() || '名称不能为空',
    });
    
    // 计算排序索引
    let orderIndex = 0;
    if (parentId) {
      const siblings = notebooks.value.filter(n => n.parent_id === parentId);
      orderIndex = siblings.length;
      console.log(`父笔记本 ${parentId} 下已有 ${siblings.length} 个子笔记本`);
    } else {
      const rootNotebooks = notebooks.value.filter(n => !n.parent_id || n.parent_id === '');
      orderIndex = rootNotebooks.length;
      console.log(`顶级已有 ${rootNotebooks.length} 个笔记本`);
    }
    
    // 创建笔记本
    const notebookData = {
      name: name.value,
      description: '',
      parent_id: parentId,
      order_index: orderIndex,
      is_deleted: 0
    };
    
    console.log('即将创建笔记本，数据:', notebookData);
    
    const notebook = await window.elec.notebook.create(notebookData);
    console.log('笔记本创建成功:', notebook);
    
    // 重新加载笔记本以更新视图
    await loadNotebooks();
    
    // 确保父笔记本展开 - 如果存在父笔记本
    if (parentId) {
      console.log(`展开父笔记本 ${parentId}`);
      expandedNotebooks.value.add(parentId);
    }
    
    // 自动展开新创建的笔记本
    expandedNotebooks.value.add(notebook.id);
    console.log(`展开新笔记本 ${notebook.id}`);
    
    // 通知父组件有变更
    emit('toggle-expand', expandedNotebooks.value);
    
    // 通知父组件笔记本创建成功
    emit('notebook-created', notebook);
    
    ElMessage.success('笔记本创建成功');
    return notebook;
  } catch (error) {
    // 过滤掉用户取消操作的错误
    if (error !== 'cancel') {
      console.error('创建笔记本失败', error);
      ElMessage.error('创建笔记本失败');
    }
    return null;
  }
};

// 编辑笔记本
const editNotebook = async (notebook: INotebook) => {
  try {
    const name = await ElMessageBox.prompt('请输入笔记本名称', '编辑笔记本', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValue: notebook.name,
      inputValidator: (value) => !!value.trim() || '名称不能为空',
    });
    
    const updatedNotebook = await window.elec.notebook.update(notebook.id, {
      name: name.value
    });
    
    // 重新加载笔记本以更新视图
    await loadNotebooks();
    
    // 通知父组件笔记本更新成功
    emit('notebook-updated', updatedNotebook);
    
    ElMessage.success('笔记本更新成功');
    return updatedNotebook;
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新笔记本失败', error);
      ElMessage.error('更新笔记本失败');
    }
    return null;
  }
};

// 删除笔记本
const deleteNotebook = async (notebook: INotebook) => {
  // 检查是否有子笔记本
  const childNotebooks = getChildNotebooks(notebook.id);
  if (childNotebooks.length > 0) {
    ElMessage.warning('请先删除子笔记本');
    return;
  }
  
  try {
    await ElMessageBox.confirm(
      '删除笔记本将同时删除其中的所有笔记，确定要删除吗？',
      '删除笔记本',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await window.elec.notebook.delete(notebook.id);
    
    // 重新加载笔记本以更新视图
    await loadNotebooks();
    
    // 通知父组件笔记本删除成功
    emit('notebook-deleted', notebook);
    
    ElMessage.success('笔记本删除成功');
    return true;
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除笔记本失败', error);
      ElMessage.error('删除笔记本失败');
    }
    return false;
  }
};

// 创建新笔记
const createNote = async (notebookId: string) => {
  if (!notebookId) {
    ElMessage.warning('请先选择一个笔记本');
    return;
  }
  
  try {
    const title = await ElMessageBox.prompt('请输入笔记标题', '新建笔记', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: (value) => !!value.trim() || '标题不能为空',
    });
    
    const note = await window.elec.note.create({
      notebook_id: notebookId,
      title: title.value,
      content: `# ${title.value}\n\n`,
      is_deleted: 0
    });
    
    // 重新加载当前笔记本的笔记
    await loadNotes(notebookId);
    
    // 确保笔记本展开
    expandedNotebooks.value.add(notebookId);
    toggleExpand(notebookId);
    
    // 通知父组件笔记创建成功
    emit('note-created', note);
    
    ElMessage.success('笔记创建成功');
    return note;
  } catch (error) {
    if (error !== 'cancel') {
      console.error('创建笔记失败', error);
      ElMessage.error('创建笔记失败');
    }
    return null;
  }
};

// 编辑笔记标题
const editNoteTitle = async (note: INote) => {
  try {
    const title = await ElMessageBox.prompt('请输入笔记标题', '编辑笔记', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValue: note.title,
      inputValidator: (value) => !!value.trim() || '标题不能为空',
    });
    
    const updatedNote = await window.elec.note.update(note.id, {
      title: title.value
    });
    
    // 重新加载当前笔记本的笔记
    await loadNotes(note.notebook_id);
    
    // 通知父组件笔记更新成功
    emit('note-updated', updatedNote);
    
    ElMessage.success('笔记标题更新成功');
    return updatedNote;
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新笔记标题失败', error);
      ElMessage.error('更新笔记标题失败');
    }
    return null;
  }
};

// 删除笔记
const deleteNote = async (note: INote) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该笔记吗？',
      '删除笔记',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await window.elec.note.delete(note.id);
    
    // 重新加载当前笔记本的笔记
    await loadNotes(note.notebook_id);
    
    // 通知父组件笔记删除成功
    emit('note-deleted', note);
    
    ElMessage.success('笔记删除成功');
    return true;
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除笔记失败', error);
      ElMessage.error('删除笔记失败');
    }
    return false;
  }
};

// 注册原生右键菜单并显示
const showContextMenu = (event: MouseEvent, type: string, target: INotebook | INote) => {
  // 阻止默认右键菜单
  event.preventDefault();
  
  const menuItems = [];
  
  if (type === 'notebook') {
    const notebook = target as INotebook;
    
    // 新建操作
    menuItems.push(
      {
        label: '新建笔记',
        accelerator: 'CmdOrCtrl+N',
        click: () => createNote(notebook.id)
      }
    );
    
    // 检查是否可以创建子笔记本
    if (canCreateChildNotebook(notebook)) {
      menuItems.push(
        {
          label: '新建子笔记本',
          accelerator: 'CmdOrCtrl+Shift+N',
          click: () => createNotebook(notebook.id)
        }
      );
    }
    
    menuItems.push({ type: 'separator' });
    
    // 编辑操作
    menuItems.push(
      {
        label: '重命名',
        accelerator: 'F2',
        click: () => editNotebook(notebook)
      }
    );
    
    menuItems.push({ type: 'separator' });
    
    // 删除操作
    menuItems.push(
      {
        label: '删除',
        accelerator: 'Delete',
        click: () => deleteNotebook(notebook)
      }
    );
  } else if (type === 'note') {
    const note = target as INote;
    
    // 编辑操作
    menuItems.push(
      {
        label: '重命名',
        accelerator: 'F2',
        click: () => editNoteTitle(note)
      }
    );
    
    menuItems.push({ type: 'separator' });
    
    // 删除操作
    menuItems.push(
      {
        label: '删除',
        accelerator: 'Delete',
        click: () => deleteNote(note)
      }
    );
  }
  
  // 调用electron的showContextMenu方法并处理回调
  try {
    window.elec.showContextMenu({
      menuItems,
      x: event.clientX,
      y: event.clientY
    });
  } catch (error) {
    console.error('显示右键菜单失败', error);
  }
};

// 暴露方法给父组件
defineExpose({
  expandedNotebooks: {
    get() {
      return expandedNotebooks.value;
    },
    set(value: Set<string>) {
      expandedNotebooks.value = value;
      
      // 为所有展开的笔记本加载笔记
      Array.from(expandedNotebooks.value).forEach(id => {
        if (!loadedNotebookIds.value.has(id)) {
          loadNotes(id).catch(e => console.error('加载笔记失败', e));
        }
      });
      
      emit('toggle-expand', expandedNotebooks.value);
    }
  },
  toggleExpand,
  loadNotebooks,
  loadNotes,
  clearLoadedCache,
  selectNotebook,
  canCreateChildNotebook,
  getChildNotebooks,
  createNotebook,
  editNotebook,
  deleteNotebook,
  createNote,
  editNoteTitle,
  deleteNote,
  showContextMenu,
  notebooks, 
  notes,
  loadedNotebookIds
});
</script>

<template>
  <div class="tree-container">
    <div v-if="loading" class="loading-indicator">正在加载...</div>
    
    <template v-else-if="notebookTree.length === 0">
      <div class="empty-tree">暂无笔记本</div>
    </template>
    
    <template v-else>
      <!-- 循环渲染递归层级 -->
      <div class="tree-level">
        <template v-for="item in notebookTree" :key="item.id">
          <div
            class="tree-item"
            :class="{
              'notebook-item': item.type === 'notebook',
              'note-item': item.type === 'note',
              'active': (item.type === 'notebook' && currentNotebook?.id === item.id) || 
                      (item.type === 'note' && currentNote?.id === item.id)
            }"
            @contextmenu="showContextMenu($event, item.type, item)"
            @click="item.type === 'notebook' ? selectNotebook(item) : $emit('select-note', item)"
          >
            <!-- 折叠图标和项目图标 -->
            <div class="item-icons">
              <span 
                v-if="item.type === 'notebook'"
                class="expand-icon"
                @click.stop="toggleExpand(item.id)"
              >
                <el-icon v-if="expandedNotebooks.has(item.id)" class="arrow-down">
                  <ArrowDown />
                </el-icon>
                <el-icon v-else class="arrow-right">
                  <ArrowRight />
                </el-icon>
              </span>
              
              <el-icon v-if="item.type === 'notebook'" class="folder-icon">
                <Folder />
              </el-icon>
              <el-icon v-else class="document-icon">
                <Document />
              </el-icon>
            </div>
            
            <!-- 项目名称 -->
            <div class="item-name">
              {{ item.type === 'notebook' ? item.name : (item as unknown as INote).title }}
            </div>
          </div>
          
          <!-- 子项容器 -->
          <div v-if="item.type === 'notebook'" 
               class="children-container"
               :style="{ maxHeight: expandedNotebooks.has(item.id) ? '1000px' : '0' }">
            <template v-for="child in item.children" :key="child.id">
              <div
                class="tree-item"
                :class="{
                  'notebook-item': child.type === 'notebook',
                  'note-item': child.type === 'note',
                  'active': (child.type === 'notebook' && currentNotebook?.id === child.id) || 
                          (child.type === 'note' && currentNote?.id === child.id)
                }"
                :style="{ paddingLeft: '8px' }"
                @contextmenu="showContextMenu($event, child.type, child)"
                @click="child.type === 'notebook' ? selectNotebook(child) : $emit('select-note', child)"
              >
                <!-- 折叠图标和项目图标 -->
                <div class="item-icons">
                  <span 
                    v-if="child.type === 'notebook'"
                    class="expand-icon"
                    @click.stop="toggleExpand(child.id)"
                  >
                    <el-icon v-if="expandedNotebooks.has(child.id)" class="arrow-down">
                      <ArrowDown />
                    </el-icon>
                    <el-icon v-else class="arrow-right">
                      <ArrowRight />
                    </el-icon>
                  </span>
                  
                  <el-icon v-if="child.type === 'notebook'" class="folder-icon">
                    <Folder />
                  </el-icon>
                  <el-icon v-else class="document-icon">
                    <Document />
                  </el-icon>
                </div>
                
                <!-- 项目名称 -->
                <div class="item-name">
                  {{ child.type === 'notebook' ? child.name : (child as unknown as INote).title }}
                </div>
              </div>
              
              <!-- 三级嵌套 -->
              <div v-if="child.type === 'notebook'" 
                   class="children-container" 
                   :style="{ 
                     paddingLeft: '8px',
                     maxHeight: expandedNotebooks.has(child.id) ? '1000px' : '0'
                   }">
                <template v-for="grandchild in child.children" :key="grandchild.id">
                  <div
                    class="tree-item"
                    :class="{
                      'notebook-item': grandchild.type === 'notebook',
                      'note-item': grandchild.type === 'note',
                      'active': (grandchild.type === 'notebook' && currentNotebook?.id === grandchild.id) || 
                              (grandchild.type === 'note' && currentNote?.id === grandchild.id)
                    }"
                    :style="{ paddingLeft: '8px' }"
                    @contextmenu="showContextMenu($event, grandchild.type, grandchild)"
                    @click="grandchild.type === 'notebook' ? selectNotebook(grandchild) : $emit('select-note', grandchild)"
                  >
                    <!-- 折叠图标和项目图标 -->
                    <div class="item-icons">
                      <span 
                        v-if="grandchild.type === 'notebook'"
                        class="expand-icon"
                        @click.stop="toggleExpand(grandchild.id)"
                      >
                        <el-icon v-if="expandedNotebooks.has(grandchild.id)" class="arrow-down">
                          <ArrowDown />
                        </el-icon>
                        <el-icon v-else class="arrow-right">
                          <ArrowRight />
                        </el-icon>
                      </span>
                      
                      <el-icon v-if="grandchild.type === 'notebook'" class="folder-icon">
                        <Folder />
                      </el-icon>
                      <el-icon v-else class="document-icon">
                        <Document />
                      </el-icon>
                    </div>
                    
                    <!-- 项目名称 -->
                    <div class="item-name">
                      {{ grandchild.type === 'notebook' ? grandchild.name : (grandchild as unknown as INote).title }}
                    </div>
                  </div>
                </template>
              </div>
            </template>
          </div>
        </template>
      </div>
    </template>
  </div>
</template>

<style scoped>
.tree-container {
  height: 100%;
  overflow: auto;
  font-size: 14px;
  user-select: none;
  padding: 8px 0;
}

.loading-indicator, .empty-tree {
  padding: 16px;
  text-align: center;
  color: var(--text-muted-color);
}

.tree-level {
  display: flex;
  flex-direction: column;
}

.tree-item {
  display: flex;
  align-items: center;
  padding: 6px 10px;
  cursor: pointer;
  border-radius: 4px;
  position: relative;
  transition: all 0.15s ease;
  margin: 2px 6px;
  line-height: 1.5;
}

.tree-item:hover {
  background-color: var(--item-hover-color);
}

.tree-item.active {
  background-color: var(--item-active-bg-color);
  color: var(--primary-color);
  font-weight: 500;
}

.notebook-item {
  color: var(--text-color);
}

.note-item {
  color: var(--text-muted-color);
}

.item-icons {
  display: flex;
  align-items: center;
  margin-right: 10px;
  min-width: 28px;
  justify-content: flex-start;
}

.expand-icon {
  display: inline-flex;
  width: 18px;
  height: 18px;
  align-items: center;
  justify-content: center;
  margin-right: 6px;
  cursor: pointer;
  transition: transform 0.15s ease;
  border-radius: 3px;
}

.expand-icon:hover {
  background-color: var(--item-hover-color);
}

.expand-icon .arrow-down,
.expand-icon .arrow-right {
  font-size: 12px;
  color: var(--text-muted-color);
  transform: rotate(0deg);
  transition: transform 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 14px;
  height: 14px;
}

.expand-icon:hover .arrow-down {
  transform: rotate(-90deg);
}

.expand-icon:hover .arrow-right {
  transform: rotate(45deg);
}

.tree-item:hover .expand-icon .arrow-down,
.tree-item:hover .expand-icon .arrow-right,
.tree-item.active .expand-icon .arrow-down,
.tree-item.active .expand-icon .arrow-right {
  color: var(--primary-color);
}

.empty-expand {
  width: 18px;
  height: 18px;
  display: inline-block;
}

/* VSCode风格的层级线 */
.children-container {
  position: relative;
  margin-left: 16px;
  padding-top: 2px;
  padding-bottom: 2px;
  overflow: hidden;
  transition: max-height 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.children-container::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 1.5px;
  background-color: var(--border-color);
  opacity: 0.7;
}

/* 确保树项目在hover状态下有更明显的视觉反馈 */
.tree-item:hover {
  background-color: var(--item-hover-color);
}

.tree-item:hover .item-icons {
  color: var(--primary-color);
}

/* 鼠标悬停在展开图标上的效果 */
.expand-icon:hover {
  background-color: rgba(128, 128, 128, 0.1);
  border-radius: 3px;
}

/* 确保当前活动项有清晰的视觉标识 */
.tree-item.active {
  background-color: var(--item-active-bg-color);
}

/* 为活动项添加更加明显但不太突兀的视觉效果 */
.tree-item.active .folder-icon,
.tree-item.active .document-icon {
  color: var(--primary-color);
}

/* 文件夹和文件图标的样式 */
.notebook-item .folder-icon {
  color: #dcb67a; /* 文件夹颜色 */
  margin-right: 3px;
  font-size: 17px;
}

.note-item .document-icon {
  color: #81a3da; /* 文件颜色 */
  margin-right: 3px;
  font-size: 16px;
}

/* 优化项目名称的样式 */
.item-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding-left: 6px;
  transition: color 0.15s ease;
}

/* 提升活动项的图标和文字可见性 */
.tree-item.active .item-name,
.tree-item.active .folder-icon,
.tree-item.active .document-icon {
  color: var(--primary-color);
}

/* 增强悬停效果 */
.tree-item:hover .item-name {
  color: var(--text-hover-color, inherit);
}
</style> 